#include "camerahandler.h"
#include <QCameraInfo>
#include <QBuffer>
VideoSurface::VideoSurface(QObject *parent)
    :QAbstractVideoSurface(parent)
{

}

QList<QVideoFrame::PixelFormat> VideoSurface::supportedPixelFormats(QAbstractVideoBuffer::HandleType) const
{
    //返回图像的处理格式
    return QList<QVideoFrame::PixelFormat>()<<QVideoFrame::Format_RGB32;
}

bool VideoSurface::present(const QVideoFrame &frame)
{
    //当前帧捕获
    emit this->videoChanged(frame);
    return true;
}

/*=========================================================================*/

cameraHandler::cameraHandler(QObject *parent) : QObject(parent),
    camera(new QCamera(parent))
{
    QCameraInfo info = QCameraInfo::defaultCamera();//返回默认相机
    camera = new QCamera(info,this);

    VideoSurface* vf = new VideoSurface(this);//生成摄像头捕获格式对象

    camera->setViewfinder(vf); //设置捕获格式
    connect(vf,&VideoSurface::videoChanged,this,&cameraHandler::onVideoChanged);

    camera->start();
}

void cameraHandler::setImageQuality(int value)
{
    imageQuality = value;
}

void cameraHandler::onVideoChanged(QVideoFrame curframe)
{
    static int i=0;
    QVideoFrame frame(curframe);
    frame.map(QAbstractVideoBuffer::ReadOnly);

    //通过当前帧的对象构建QImage图片对象
    QImage image(frame.bits(),
                 frame.width(),frame.height(),
                 QVideoFrame::imageFormatFromPixelFormat(frame.pixelFormat()));

    frame.unmap();

    //旋转图像180
    QMatrix matrix;
    matrix.rotate(180);
    image = image.transformed(matrix);
//    image = image.scaled(160,160,Qt::KeepAspectRatio,Qt::SmoothTransformation); //160*160像素



    if((i%4) == 0)
    {
        QByteArray byteArray;

        QBuffer buffer(&byteArray);
        buffer.open(QIODevice::WriteOnly);

        // 设置压缩质量（0-100，数值越大质量越高）
        int quality = this->imageQuality;

        // 将压缩后的图片数据写入 QBuffer
        image.save(&buffer, "JPG", quality);

        // 关闭 QBuffer
        buffer.close();



        // 重新加载压缩后的数据为 QImage
        QImage loadedImage;
        loadedImage.loadFromData(byteArray);

        qDebug()<<"压缩前:"<<image.sizeInBytes()<<"压缩后:"<<byteArray.size()<<"变化后"<<loadedImage.sizeInBytes();
        emit sendVideo(byteArray);
        emit videoUpdated(loadedImage);
    }
    i++;
}

